package com.zhongxi.guoyuan.fragment.RewardCoinOrder;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.coinPost.LogisiticsInfoAdapter;
import com.zhongxi.guoyuan.adapter.rewardCoinOrder.RewardOrderHasNoApplyAdapter;
import com.zhongxi.guoyuan.adapter.rewardCoinOrder.RewardOrderHasNoReceiverAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.coinPost.LogisiticsData;
import com.zhongxi.guoyuan.entity.coinPost.LogisiticsResult;
import com.zhongxi.guoyuan.entity.rewardcoin.RewardCoinOrderInfo;
import com.zhongxi.guoyuan.entity.rewardcoin.RewardCoinOrderResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.utils.QRCodeUtils;
import com.zhongxi.guoyuan.view.coinPostShot.CoinEvaluateActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class RewardOrderHasNoReceiverFragment extends BaseFragment implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

    private PullToRefreshListView lvList;
    private List<RewardCoinOrderInfo> data = new ArrayList<>();
    private RewardOrderHasNoReceiverAdapter adapter;
    private int pos = -1;
    private String type;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //确认收货
            pos = (int) msg.obj;
            switch (msg.what) {
                case 0:
                    //去投诉
                    showCommentWindow();
                    break;
                case 1:
                    //确认收货
                    postConfirmGet();
                    break;
                case 2:
                    showLogistics();
                    break;
                case 3:
                    getCode();
                    break;

            }

        }
    };

    private ListView listView;
    private LogisiticsInfoAdapter infoAdapter;
    private String content;
    private Map<String, String> map = new HashMap<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_order_has_no_apply, container, false);
    }

    @Override
    protected void initView() {
        super.initView();
        lvList = (PullToRefreshListView) getView().findViewById(R.id.lvList);
        lvList.setMode(PullToRefreshBase.Mode.BOTH);
        adapter = new RewardOrderHasNoReceiverAdapter(context, data, handler,this);
        lvList.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        super.initData();
        getOrder();
        TextView tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setText("亲,暂时还没有数据哦!");
        tv.setTextSize(20);
        //当界面为空的时候显示的视图
        lvList.setEmptyView(tv);
    }

    /**
     * 获取待收货订单
     */
    private void getOrder() {
        type = "order";
        String str = "&page=" + pageNum;
        getServer(Url.REWARD_TORECEIPT, null, str, false, null, "get");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden)
        getOrder();
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if (type.equals("order")) {
                RewardCoinOrderResult result = gson.fromJson(response, RewardCoinOrderResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                if (pageNum == 1) {
                    data.clear();
                }
                JSONObject obj = new JSONObject(response);
                if (result.getOrderInfo() != null && result.getOrderInfo().size() > 0) {
                    List<RewardCoinOrderInfo> orderInfo = result.getOrderInfo();
                    data.addAll(orderInfo);
                    JSONObject info = obj.optJSONObject("orderMirror");
                    adapter.setInfo(info);
                    JSONObject shopInfo = obj.optJSONObject("shopInfo");
                    adapter.setShopInfo(shopInfo);
                }
                JSONObject post = obj.optJSONObject("post");
                if (post != null && post.length() > 0) {
                    adapter.setPost(post);
                }
                JSONObject toDoor = obj.optJSONObject("todoor");
                if (toDoor != null && toDoor.length() > 0) {
                    adapter.setToDoor(toDoor);
                }
                adapter.notifyDataSetChanged();
                lvList.onRefreshComplete();

            } else if (type.equals("confirm")) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                data.remove(pos);
                adapter.notifyDataSetChanged();
            } else if ("logistics".equals(type)) {
                LogisiticsResult result = gson.fromJson(response, LogisiticsResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                LogisiticsData logisitics = result.getData();
                showLogisticsInfo(logisitics);
            } else if ("comment".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                getOrder();
            } else if ("code".equals(type)) {
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                JSONObject resJson = new JSONObject(response);
                JSONObject orderCus = resJson.optJSONObject("orderCus");
                String deliverycode = orderCus.optString("deliverycode");
                String qrcode = resJson.optString("qrcode");
                showQrCode(deliverycode,qrcode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);

        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }

            if (1000 == result.getCode()) {
                showShortToast("参数错误");
            } else if (2016 == result.getCode()) {
                showShortToast("订单信息不完整");
            } else if (1001 == result.getCode()) {
                showShortToast("未登录");
            } else if (2017 == result.getCode()) {
                showShortToast("未发货");
            } else if (1558 == result.getCode()) {
                showShortToast("已投诉");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 去投诉
     */
    private void showCommentWindow() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_to_complaint, null);
        final EditText editText = (EditText) view.findViewById(R.id.etTips_fuwu);
        final TextView textView = (TextView) view.findViewById(R.id.tvNum_fuwu);
        TextView submit = (TextView) view.findViewById(R.id.tv_submit_complaint);
        ImageView cancel = (ImageView) view.findViewById(R.id.post_nopay_ivCancel);
        builder.setView(view);
        final AlertDialog dialog = builder.create();

        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                MyTextUtils.TextChangeUtils(context, textView, editable, 150);
            }
        });


        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                content = editText.getText().toString().trim();

                if (null != content && !"".equals(content)) {
                    getComplaint(content);
                    dialog.dismiss();
                } else {
                    showShortToast("请输入您的意见！");
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }


    /**
     * 确认收货
     */
    private void postConfirmGet() {
        type = "confirm";
        map.clear();
        map.put("ordertype", data.get(pos).getOrdertype());
        map.put("orderid", data.get(pos).getId());
        map.put("shopid", data.get(pos).getShopid());

        getServer(Url.REWARD_TOCONFIRM, map, "", false, null, "post");
    }

    /**
     * @param content
     */
    private void getComplaint(String content) {
        type = "comment";
        map.clear();
        map.put("ordertype", data.get(pos).getOrdertype());
        map.put("orderid", data.get(pos).getId());
        map.put("shopid", data.get(pos).getShopid());
        map.put("content", content);
        getServer(Url.REWARD_TOCOMPLAIN, map, "", false, null, "post");
    }

    /**
     * 看物流信息
     */
    private void showLogistics() {
        type = "logistics";
        map.clear();
        map.put("orderid", data.get(pos).getId());

        getServer(Url.LOGISTICS_INFO, map, "", false, null, "post");
    }

    /**
     * 物流时间轴
     */
    private void showLogisticsInfo(LogisiticsData logisitics) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.post_show_logisitics, null);
        ImageView back = (ImageView) view.findViewById(R.id.post_logisitics_back);
        TextView company = (TextView) view.findViewById(R.id.post_logisitics_company);
        TextView number = (TextView) view.findViewById(R.id.post_logisitics_number);
        ListView list = (ListView) view.findViewById(R.id.post_logisitics_list);
        TextView error = (TextView) view.findViewById(R.id.logisitics_error);
        builder.setView(view);

        final AlertDialog dialog = builder.create();
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        if (!logisitics.getState().equals("4")) {
            company.setText("快递公司:" + logisitics.getShipper());
            number.setText("运单编号:" + logisitics.getLogisticCode());
            infoAdapter = new LogisiticsInfoAdapter(getContext());
            list.setAdapter(infoAdapter);
            List<LogisiticsData.Traces> traces = logisitics.getTraces();
            Collections.reverse(traces);
            infoAdapter.setList(traces);
        } else {
            list.setVisibility(View.GONE);
            error.setVisibility(View.VISIBLE);
        }
        dialog.show();
        WindowManager windowManager = getActivity().getWindowManager();
        Display defaultDisplay = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
        attributes.height = (int) (defaultDisplay.getHeight() * 0.7);
        dialog.getWindow().setAttributes(attributes);
    }

    /**
     * 获取提货码
     */
    private void getCode() {
        type = "code";
        map.clear();

        map.put("orderid", data.get(pos).getId());
        map.put("shopid", data.get(pos).getShopid());

        getServer(Url.REWARD_GET_DELIVERCODE, map, "", false, null, "post");
    }


    /**
     * 查看提货码
     * @param deliverycode
     * @param qrcode
     */
    private void showQrCode(String deliverycode, String qrcode) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_to_qrcode, null);
        final EditText editText = (EditText) view.findViewById(R.id.etTips_fuwu);

        final TextView submit = (TextView) view.findViewById(R.id.tv_submit_complaint);
        ImageView cancel = (ImageView) view.findViewById(R.id.post_nopay_ivCancel);
        final ImageView code = (ImageView) view.findViewById(R.id.iv_qrcode);

        builder.setView(view);
        final AlertDialog dialog = builder.create();

        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();


        editText.setText("提货码：" + deliverycode);
        code.setVisibility(View.VISIBLE);
        code.setImageBitmap(QRCodeUtils.createQRCode2(qrcode, 200));
        submit.setVisibility(View.GONE);


        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    @Override
    protected void initEvent() {
        super.initEvent();
        lvList.setOnItemClickListener(this);
        lvList.setOnRefreshListener(this);
        listView = lvList.getRefreshableView();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position - 1 == adapter.getmExpandedMenuPos()) {
            adapter.setmExpandedMenuPos(-1);
        } else {
            adapter.setmExpandedMenuPos(position - 1);
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(position);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getOrder();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getOrder();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
        if (requestCode == 998 && CoinEvaluateActivity.EVALUATE_RESULT_CODE == resultCode) {
            if (pos >= 0) {
                data.remove(pos);
                adapter.notifyDataSetChanged();
            }
        }
    }
}
